#!/usr/bin/python

# Copyright (c) 2010-, WangFei, Cloud Team, CGCL,
# All rights reserved.
# This Program launch a job to a mpi environment.
# python lanuch master_ip master_ip_root_password "mpi_job_execute_argv"
# python launch 192.168.226.167 passw0rd "mpirun -machinefile /home/cgcl/all_vm_ip_list -np 2 /home/cgcl/cpi"
import os, sys
import paramiko
import MySQLdb
import string
import time

def isDigtal(myNum):
    nums = string.digits
    if type(myNum) is not str:
        return False
    else:
        for temp in myNum:
            if temp not in nums:
                return False
        return True

def checkParameter(conn):
    global job_id
    if not conn:
        print "Can not connect to database, Fail!"
        return -1
    paraCnt=len(sys.argv)
    if paraCnt != 2:
        return 0
    job_id=str(sys.argv[1])
    if not isDigtal(job_id):
        return 0
    
    flag = conn.execute("select job_id from jobs where job_id = " + job_id);
    if flag == 0:
        print "No Job ", job_id
        return 0
    return 1

def test(master_address,user,password,ssh_port):
    command="mpdtrace -l"
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.connect((master_address), username=(user), password=(password), port=(ssh_port))
    stdin,stdout,stderr = client.exec_command(command)
    print stdout.read()
    client.close()

def getinfo(conn,job_id):
    global masterIP
    global password
    global total_VM    
    cnt = conn.execute("select vm_ip,vm_root_password from job_resource, vm_info where job_id="+job_id+" and job_resource.vm_id=vm_info.vm_id and vm_info.vm_type='master_node'")
    if cnt != 1:
        print "Not Master Node,Fail!"
        return 0
    rows=conn.fetchall()
    masterIP=rows[0][0]
    password=rows[0][1]
 

job_id="0"
masterIP="0"
password="0"
tr_command="command format:\n" + \
"   mpitest job_id\n" + \
"   For example: mpitest 1"

if __name__ == "__main__":
    connect=MySQLdb.connect(host="localhost",port=3306,user="root",passwd="passw0rd",db="cloud")
    conn=connect.cursor()
    #print connect,conn
    flag = checkParameter(conn)
    if flag == -1:
        sys.exit(0)
    if flag == 0:
        print str_command
        sys.exit(0)
    
    getinfo(conn,job_id)
    test(masterIP,"root",password,22)      
    conn.close()
    connect.close()


